package com.yantu.controller.admin;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.yantu.bean.*;
import com.yantu.bean.Class;
import com.yantu.mapper.*;
import com.yantu.util.JWTUtil;
import com.yantu.util.RedisUtils;
import com.yantu.util.Result;
import com.yantu.view.PageView;
import com.yantu.view.admin.AdminPageView;
import io.swagger.annotations.ApiModel;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author 综合实训课程设计
 * @since 2022-08-07
 */
@RestController
@RequestMapping("/admin")
@ApiModel("管理端用户接口")
public class AdminUserController extends AdminUserEventLogController{

    @Autowired
    RedisUtils redisUtils;

    @Autowired
    UserMapper userMapper;

    @Autowired
    ClassMapper classMapper;

    @Autowired
    JWTUtil jwtUtil;

    @Autowired
    QuestionMapper questionMapper;

    @Autowired
    ExamPaperAnswerMapper examPaperAnswerMapper;

    @Autowired
    ExamPaperQuestionCustomerAnswerMapper examPaperQuestionCustomerAnswerMapper;

    @Autowired
    ExamPaperMapper examPaperMapper;

    //首页
    @GetMapping("/dashboard")
    @ApiOperation("获取数据总数信息")
    public  Result infoCount(){
        if(redisUtils.haskeysf("adminDataCount")){
            System.out.println("缓存里面有");
            Map map = (Map) redisUtils.getValue("adminDataCount");
            return Result.succ(200, "查询成功", map);
        }else {
            Map map = new HashMap<>();
            map.put("examPaperCount", examPaperMapper.selectCount(null));
            map.put("questionCount", questionMapper.selectCount(null));
            map.put("doExamPaperCount", examPaperAnswerMapper.selectCount(null));
            map.put("doQuestionCount", examPaperQuestionCustomerAnswerMapper.selectCount(null));
            redisUtils.saveValue("adminDataCount",map);
            return Result.succ(200, "查询成功", map);
        }
    }

    //用户分页
    @GetMapping("/users")
    @ApiOperation("用户分页信息")
    public Result myListUser(@ModelAttribute PageView pageView) {
        PageHelper.startPage(pageView.getPageIndex(), pageView.getPageSize());
        if(redisUtils.haskeysf("adminUserList"+pageView)){
            System.out.println("缓存里面有");
            PageInfo pageInfo = (PageInfo) redisUtils.getValue("adminUserList"+pageView);
            return Result.succ(200, "查询成功", pageInfo);
        }else {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            if (pageView.getRole() != null) {
                queryWrapper.eq("role", pageView.getRole());
            }
            List<User> userList = userMapper.selectList(queryWrapper);
            PageInfo pageInfo = new PageInfo(userList);
            redisUtils.saveValue("adminUserList"+pageView,pageInfo);
            return Result.succ(200, "查询成功", pageInfo);
        }
    }

    //用户查询
    @GetMapping("/user/{name}")
    @ApiOperation("根据用户name查询用户")
    public Result getUserById(@PathVariable("name") String name) {
        if(redisUtils.haskeysf("adminUserList"+name)){
            System.out.println("缓存里面有");
            List<User> users = (List<User>) redisUtils.getValue("adminUserList"+name);
            return Result.succ(200, "查询成功", users);
        }else {
            QueryWrapper<User> queryWrapper = new QueryWrapper<>();
            queryWrapper.like("user_name", name);
            List<User> users = userMapper.selectList(queryWrapper);
            System.out.println(users);
            if (users != null) {
                redisUtils.saveValue("adminUserList"+name,users);
                return Result.succ(200, "查询成功", users);
            } else {
                return Result.fail("没有该用户");
            }
        }
    }

    //用户编辑
    @PutMapping("/user")
    @ApiOperation("编辑用户信息")
    public Result editUserMessage(@RequestBody User user) {

        UpdateWrapper updateQuery = new UpdateWrapper<>();
        updateQuery.eq("id",user.getId());
        if(user.getUserName()!=null){
        updateQuery.set("user_name",user.getUserName());}
        if(user.getPassword()!=null){
        updateQuery.set("password",user.getPassword());}
        if(user.getRealName()!=null){
        updateQuery.set("real_name",user.getRealName());}
        if(user.getRole()!=null){
        updateQuery.set("role",user.getRole());}
        if(user.getStatus()!=null){
        updateQuery.set("status",user.getStatus());}
        if(user.getAge()!=null){
        updateQuery.set("age",user.getAge());}
        if(user.getSex()!=null){
        updateQuery.set("sex",user.getSex());}
        if(user.getBirthDay()!=null){
        updateQuery.set("birth_day",user.getBirthDay());}
        if(user.getPhone()!=null){
        updateQuery.set("phone",user.getPhone());}
        if(user.getUserLevel()!=null){
        updateQuery.set("user_level",user.getUserLevel());}
        int result  = userMapper.update(null,updateQuery);
        if(result>0){
            super.adminLog("admin 成功编辑个人用户"+user.getUserName()+"信息");
            User user1 = userMapper.selectById(user.getId());
            System.out.println(user1);
            redisUtils.delAll();
            return Result.succ(200,"编辑成功",user1);
        }else {
            return Result.fail("编辑失败");
        }
    }

    //获取当前个人用户信息
    @GetMapping("/user")
    @ApiOperation("获取当前用户个人信息")
    public Result getUserInfo(HttpServletRequest request){
        //获取请求头token
        String token = request.getHeader("Authorization");
        //根据
        if(redisUtils.haskeysf("adminUser"+token)){
            System.out.println("缓存里面有");
            Map map = (Map) redisUtils.getValue("adminUser"+token);
            return Result.succ(200, "查询成功", map);
        }else {
            QueryWrapper<User> query = new QueryWrapper<>();
            query.eq("token", token);
            User user = userMapper.selectOne(query);
            if (user == null) {
                return Result.fail("获取失败", null);
            }
            //把查询到的信息放在需要的视图里面并返回给前端
            Map<String, Object> map = new HashMap<>();
            map.put("id", user.getId());
            map.put("userName", user.getUserName());
            map.put("realName", user.getRealName());
            map.put("age", user.getAge());
            map.put("role", user.getRole());
            map.put("sex", user.getSex());
            map.put("birthDay", user.getBirthDay());
            map.put("phone", user.getPhone());
            map.put("createTime", user.getCreateTime());
            map.put("lastActiveTime", user.getLogintime());
            map.put("status", user.getStatus());
            map.put("userLevel", user.getUserLevel());
            map.put("imagePath", user.getImagePath());
            redisUtils.saveValue("adminUser" + token, map);
            return Result.succ(200, "获取成功", map);
        }
    }

    //个人信息修改
    @PutMapping("/userInfo")
    @ApiOperation("个人信息修改")
    public Result editMyInfo(HttpServletRequest request,@ModelAttribute User user){
        //获取请求头token
        String token = request.getHeader("Authorization");
        QueryWrapper<User> query = new QueryWrapper<>();
        query.eq("token",token);
        User user1 = userMapper.selectOne(query);
        if (user1==null){
            return Result.fail("获取失败",null);
        }
        UpdateWrapper updateQuery=new UpdateWrapper();
        updateQuery.eq("id",user1.getId());
        if(user.getUserName()!=null){
            updateQuery.set("user_name",user.getUserName());}
        if(user.getRealName()!=null){
            updateQuery.set("real_name",user.getRealName());}
        if(user.getRole()!=null){
            updateQuery.set("role",user.getRole());}
        if(user.getStatus()!=null){
            updateQuery.set("status",user.getStatus());}
        if(user.getAge()!=null){
            updateQuery.set("age",user.getAge());}
        if(user.getSex()!=null){
            updateQuery.set("sex",user.getSex());}
        if(user.getBirthDay()!=null){
            updateQuery.set("birth_day",user.getBirthDay());}
        if(user.getPhone()!=null){
            updateQuery.set("phone",user.getPhone());}
        if(user.getUserLevel()!=null){
            updateQuery.set("user_level",user.getUserLevel());}
        if(user.getImagePath()!=null){
            updateQuery.set("image_path",user.getImagePath());}
        int result  = userMapper.update(null,updateQuery);
        if(result>0){
            User user2 = userMapper.selectById(user.getId());
            super.adminLog("admin 个人用户"+user.getUserName()+"信息编辑成功");
            System.out.println(user1);
            redisUtils.delAll();
            return Result.succ(200,"编辑成功",user2);
        }else {
            return Result.fail("编辑失败");
        }
    }

    //用户删除
    @DeleteMapping("/user/{id}")
    @ApiOperation("删除用户")
    public Result deleteUser(@PathVariable("id") Integer id) {

        int result = userMapper.deleteById(id);
        if(result>0){
            super.adminLog("admin 成功删除用户"+id+"信息");
            redisUtils.delAll();
            return Result.succ("删除成功",null);
        }else {
            return Result.fail("删除失败");
        }
    }

    //用户日志
    @GetMapping("/userLogList ")
    @ApiOperation("分页用户日志列表")
    public Result userLogList(@ModelAttribute AdminPageView pageView){
        System.out.println("进来了吗");
        PageHelper.startPage(pageView.getPageIndex(), pageView.getPageSize());
        if(redisUtils.haskeysf("adminUserEventLog"+pageView)){
            System.out.println("缓存里面有");
            PageInfo pageInfo = (PageInfo) redisUtils.getValue("adminUserEventLog"+pageView);
            return Result.succ(200, "查询成功", pageInfo);
        }else {
            QueryWrapper<UserEventLog> queryWrapper = new QueryWrapper<>();
            if (pageView.getUserId() != null) {
                queryWrapper.eq("user_id", pageView.getUserId());
            }
            if (pageView.getUserName() != null) {
                queryWrapper.eq("user_name", pageView.getUserName());
            }
            List<UserEventLog> userEventLogList = userEventLogMapper.selectList(queryWrapper);
            PageInfo pageInfo = new PageInfo(userEventLogList);
            redisUtils.saveValue("adminUserEventLog" + pageView, pageInfo);
            return Result.succ(200, "查询成功", pageInfo);
        }
    }

    //用户状态修改
    @PutMapping("/user/{id}")
    @ApiOperation("修改用户状态")
    public Result editUserByState(@PathVariable("id") Integer id) {
        User user = userMapper.selectById(id);
        UpdateWrapper updateQuery = new UpdateWrapper<>();
        updateQuery.eq("id",user.getId());
        if(user.getStatus()==0){
            updateQuery.set("status",1);
        }else {
            updateQuery.set("status",0);
        }
        int result = userMapper.update(null,updateQuery);
        if(result>0){
            super.adminLog("admin 成功修改用户"+id+"状态");
            redisUtils.delAll();
            return Result.succ(200,"修改成功",null);
        }else {
            return Result.fail("修改失败");
        }

    }


}
